import React, { useEffect, useState, useRef } from "react";
import { PlusOutlined } from "@ant-design/icons";
import {
  Table,
  Space,
  Input,
  Select,
  Form,
  Button,
  Radio,
  Upload,
  Flex,
  Modal,
  message,
  Pagination,
} from "antd";
import moment from "moment";
import {
  userGet,
  UserDelete,
  AccountDeleteGet,
  UserEdit,
  departnamesGet,
  userItem,
  AccountGet,
} from "../../../request/xxApi";
import Department from "../../../styles/DepartmentManagement.module.css";
import "../../../assets/xxAssets/font_4791525_1loqcwtpe32h/iconfont.css";
const getBase64 = (file) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = (error) => reject(error);
  });
};
const DepartmentManagement = () => {
  const [selectedRowKeys, setSelectedRowKeys] = useState([]); //保存每条数据的选中状态
  const [loading, setLoading] = useState(false); //弹出框显隐
  const [data, setData] = useState([]); //所有数据
  const [deteleid, setdeteleid] = useState(); //删除的数据id
  const [currentPage, setCurrentPage] = useState(1); //当前页
  const [pageSize, setPageSize] = useState(10); //当前页数量
  const [open, setOpen] = useState(false); //model的显隐
  const [open1, setOpen1] = useState(false); //model的显隐
  const [doctorAll, setDoctorAll] = useState(); //所有权限的信息下拉框使用
  const [total, setTotal] = useState(0); // 总数据数量
  const [form] = Form.useForm(); //表单
  const currentRecordRef = useRef();
  const inputRef = useRef(); //查询信息
  const [searchKeyword, setSearchKeyword] = useState("");
  const [currentUserRole, setCurrentUserRole] = useState(""); //登陆用户的权限
  const [userinfo, setUserinfo] = useState([]);
  const [permission, setPermission] = useState(true); //权限
  const [previewOpen, setPreviewOpen] = useState(false);
  const [previewImage, setPreviewImage] = useState("");
  const [previewTitle, setPreviewTitle] = useState("");
  const [file, setFile] = useState(null); //上传返回图片的路径
  const handleCance = () => setPreviewOpen(false);
  const [ItemOpen,setItemOpen]=useState(false)

  useEffect(() => {
    //分页获取数据
    fetchData(currentPage, pageSize, searchKeyword);
    //本地存储 存储登陆信息
    const userData = localStorage.getItem("userInfo");
    const parsedData = JSON.parse(userData);
    setCurrentUserRole(parsedData.purview);
  }, [currentPage, pageSize, searchKeyword]);

  useEffect(() => {
    //获取所有数据将权限筛选出来
    userGet({ page: 1, size: 100 }).then((res) => {
      res.data.forEach((item) => {
        if (userinfo.indexOf(item.purview) === -1) {
          setUserinfo([...userinfo, item.purview]);
        }
      });
    });
  });
  //获取账号列表
  const fetchData = async (page, size, keyword = "") => {
    setLoading(true);
    try {
      const res = await AccountGet({ page, size, name: keyword });
      const formattedData = res.data.map((item) => ({
        ...item,
        createtime: moment(item.createtime).format("YYYY-MM-DD"), //时间格式转换
      }));
      setData(formattedData); //账号列表
      setTotal(res.total); //总数量
    } catch (error) {
      console.error("Failed to fetch data:", error);
    } finally {
      setLoading(false);
    }
  };
  //图片上传
  const handlePreview = (file) => {
    if (!file.url && !file.preview) {
      file.preview = getBase64(file.originFileObj);
    }
    setPreviewImage(file.url || file.preview);
    setPreviewOpen(true);
    setPreviewTitle(
      file.name || file.url.substring(file.url.lastIndexOf("/") + 1)
    );
  };
  //图片上传
  const handleChange = (info) => {
    const { fileList } = info;
    setFile(() => {
      if (fileList.length === 1) {
        return fileList[0];
      }
      return null;
    });
  };

  const uploadButton = (
    <div>
      <PlusOutlined />
      <div style={{ marginTop: 8 }}>Upload</div>
    </div>
  );
  //表格配置
  const columns = [
    {
      title: "账号",
      dataIndex: "account",
      key: "account",
      width: 200,
      align: "center",
    },
    {
      title: "权限",
      dataIndex: "purview",
      key: "purview",
      align: "center",
    },
    {
      title: "姓名",
      dataIndex: "name",
      key: "name",
      align: "center",
    },
    {
      title: "性别",
      dataIndex: "sex",
      key: "sex",
      align: "center",
    },
    {
      title: "手机号",
      dataIndex: "phone",
      key: "phone",
      align: "center",
    },
    {
      title: "科室操作",
      key: "action",
      align: "center",
      width: 170,
      render: (text, record) => (
        <div className={Department.cellStyle}>
          <Space size="middle">
          <span
              className="iconfont icon-wendang"
              onClick={() => userinfoClick(record.id)}
              style={{ color: "#3892F7" , cursor: "pointer"}}
            ></span>
            <span
              className="iconfont icon-shanchu"
              onClick={() => deleteCLick(record.id)}
              style={{ color: "#3892F7" ,cursor: "pointer"}}
            ></span>
            <span
              className="iconfont icon-a-bianji1"
              onClick={() => EditCLick(record)}
              style={{ color: "#3892F7" , cursor: "pointer"}}
            ></span>
          </Space>
        </div>
      ),
    },
  ];

  //行选择状态
  const onSelectChange = (newSelectedRowKeys) => {
    setSelectedRowKeys(newSelectedRowKeys);
  };

  //行选择状态
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };

  //批量删除是否可点
  const hasSelected = selectedRowKeys.length > 0;

  //删除 拿数据id
  const deleteCLick = (id) => {
    setdeteleid(id);
    setOpen(true);
  };

  const onShowSizeChange = (current, size) => {
    setPageSize(size);
    setCurrentPage(1); // 当改变每页显示条数时，通常回到第一页
    fetchData(1, size, searchKeyword);
  };

  const handleOk = () => {
    setLoading(true);
    setTimeout(() => {
      setLoading(false);
      setOpen(false);
    }, 1000);
  };
  //取消
  const handleOkClick = () => {
    setOpen1(false);
  };

  const handleCancel = () => {
    AccountDeleteGet({ id: deteleid }).then((res) => {
     if(res.code===1){
        message.success('修改成功');
        fetchData(currentPage, pageSize, searchKeyword);
     }
    });
    setOpen(false);
  };
  const handleCancelClick = () => {
    setOpen1(false); // 关闭 Modal
    form.resetFields(); // 重置表单
  };

  //修改
  const EditCLick = (record) => {
    setdeteleid(record.id);
    departnamesGet().then((res) => {
      const doctors = userinfo.map((doctor) => ({
        label: doctor,
        value: doctor,
      }));
      setDoctorAll(doctors);
      setOpen1(true); // 打开编辑模态框

      userItem({ id: record.id }).then((res) => {
        if (currentUserRole === "医务管理员") {
          setPermission(false);
        } else if (res.data[0].purview !== currentUserRole) {
          setPermission(true); // 设置权限为禁用
        } else {
          setPermission(false);
        }
        setPreviewImage(res.data[0].head);
        form.setFieldsValue({
          account: res.data[0].account,
          name: res.data[0].name,
          password: res.data[0].password,
          phone: res.data[0].phone,
          purview: res.data[0].purview,
          idcard: res.data[0].idcard,
          sex: res.data[0].sex,
          url: res.data[0].head,
        });
      });
    });
  };

  const handlePageChange = (page) => {
    setCurrentPage(page);
    fetchData(page, pageSize, searchKeyword); // 执行分页查询，保持查询关键字不变
  };

  //修改表单确认修改
  const onFormFinish = (values) => {
    const url = file?.response?.header;
    const id = deteleid;
    if (url) {
      values = {
        ...values,
        url,
        id,
      };
    } else {
      values = {
        ...values,
        id,
      };
    }
    UserEdit(values).then((res) => {
    if(res.code===1){
      message.success('修改成功');
      fetchData(currentPage, pageSize, searchKeyword);
    }
    });
   

    setOpen1(false);
  };

  const handleSearch = () => {
    const value = inputRef.current.input.value;
    setSearchKeyword(value); // 更新查询关键字状态
    setCurrentPage(1); // 重置到第一页
    fetchData(1, pageSize, value); // 执行查询
  };

  const handleDeleteSelected = async () => {
    if (selectedRowKeys.length === 0) {
      // 如果没有选中的项，则不执行任何操作
      message.warning("请选择要删除的项");
      return;
    }
    setLoading(true);
      // 调用封装好的批量删除请求方法
      const data=JSON.stringify(selectedRowKeys)
      const response = await UserDelete({ ids: data });
      if (response.code === 1) {
        message.success("批量删除成功");
        setSelectedRowKeys([]); // 清空选中的项
        setCurrentPage(1); // 重置到第一页
        fetchData(currentPage, pageSize, searchKeyword);
      } 
  };

  const yesClick = () => {
    setOpen1(false);
  };
  //查看详情
  const userinfoClick=(id)=>{
    userItem({ id: id }).then((res) => {
        // setPreviewImage(res.data[0].head);
        const newImageUrl = res.data[0].head.replace("http://192.168.109.17:21001", "http://localhost:21001");
        setPreviewImage(newImageUrl);
        form.setFieldsValue({
          account: res.data[0].account,
          name: res.data[0].name,
          password: res.data[0].password,
          phone: res.data[0].phone,
          purview: res.data[0].purview,
          idcard: res.data[0].idcard,
          sex: res.data[0].sex,
          url: newImageUrl,
        });
      });
      setItemOpen(true)
  }

  const handleItemClick=()=>{
    setItemOpen(false); 
    form.resetFields(); 
  }
  const handleOkItemClick=()=>{
    setItemOpen(false); 

  }
  return (
    <>
      <div className={Department.box}>
        <Modal
          open={open}
          title="系统提示"
          onCancel={handleCancel}
          footer={null}
        >
          <p className={Department.modal_text}>
            您正在进行科室删除操作，此操作不可逆，确定要删除对应科室吗？
          </p>
          <div className={Department.modal_btn_box}>
            <Button
              key="back"
              className={Department.modal_btn}
              onClick={handleCancel}
            >
              确定删除
            </Button>
            <Button
              key="submit"
              className={Department.modal_btn}
              type="primary"
              loading={loading}
              onClick={handleOk}
            >
              取消
            </Button>
          </div>
        </Modal>
        <Modal
          open={open1}
          title="编辑科室"
          onOk={handleOkClick}
          onCancel={handleCancelClick}
          footer={null}
        >
          <Form
            onFinish={onFormFinish}
            form={form}
            style={{
              marginTop: "20px",
              maxWidth: 600,
            }}
          >
            <Form.Item name="account" labelCol={{ span: 4 }} label="医务账号">
              <Input
                disabled={currentUserRole !== "医务管理员"}
                placeholder={
                  currentRecordRef.current ? currentRecordRef.current.name : ""
                }
              />
            </Form.Item>
            <Form.Item name="purview" labelCol={{ span: 4 }} label="权限">
              <Select
                placeholder="选择权限"
                disabled={permission}
                options={doctorAll}
              />
            </Form.Item>
            <Form.Item name="password" labelCol={{ span: 4 }} label="账号密码">
              <Input
                value={
                  currentRecordRef.current
                    ? currentRecordRef.current.password
                    : ""
                }
                disabled={permission}
              />
            </Form.Item>
            <Form.Item name="idcard" labelCol={{ span: 4 }} label="身份证号">
              <Input
                disabled
                value={
                  currentRecordRef.current ? currentRecordRef.current.id : ""
                }
              />
            </Form.Item>
            <Form.Item name="phone" labelCol={{ span: 4 }} label="手机号">
              <Input
                disabled={permission}
                value={
                  currentRecordRef.current ? currentRecordRef.current.phone : ""
                }
              />
            </Form.Item>
            <Form.Item name="sex" labelCol={{ span: 4 }} label="性别">
              <Input
              disabled
                value={
                  currentRecordRef.current ? currentRecordRef.current.sex : ""
                }
              />
            </Form.Item>
            <Form.Item name="url" labelCol={{ span: 4 }} label="头像">
              <div>
                <Upload
                  action="http://localhost:21001/users/uploadheader"
                  listType="picture-card"
                  fileList={file ? [file] : []}
                  onPreview={handlePreview}
                  method="POST"
                  maxCount={1} // 限制只能上传一个文件
                  onChange={handleChange}
                >
                  {file ? (
                    uploadButton
                  ) : (
                    <img
                      alt="example"
                      style={{ width: "100%" }}
                      src={previewImage}
                    />
                  )}
                </Upload>
                <Modal
                  open={previewOpen}
                  title={previewTitle}
                  footer={null}
                  onCancel={handleCance}
                >
                  <img
                    alt="example"
                    style={{ width: "100%" }}
                    src={previewImage}
                  />
                </Modal>
              </div>
            </Form.Item>
            <Form.Item>
              <div className={Department.director_btn_box}>
                {!permission ? (
                  // 如果 permission 为 true，显示确认修改和取消按钮
                  <>
                    <Button
                      className={Department.modal_btn}
                      type="primary"
                      htmlType="submit"
                    >
                      确认修改
                    </Button>
                    <Button
                      key="cancel"
                      className={Department.modal_btnn}
                      loading={loading}
                      onClick={handleOkClick}
                    >
                      取消
                    </Button>
                  </>
                ) : (
                  // 否则显示确认按钮
                  <Button
                    className={Department.btn}
                    type="primary"
                    onClick={yesClick}
                  >
                    确认
                  </Button>
                )}
              </div>
            </Form.Item>
          </Form>
        </Modal>
        <Modal
          open={ItemOpen}
          title="编辑科室"
          onOk={handleOkItemClick}
          onCancel={handleItemClick}
          footer={null}
        >
          <Form
            onFinish={onFormFinish}
            form={form}
            style={{
              marginTop: "20px",
              maxWidth: 600,
            }}
          >
            <Form.Item name="account" labelCol={{ span: 4 }} label="医务账号">
              <Input
                disabled
                placeholder={
                  currentRecordRef.current ? currentRecordRef.current.name : ""
                }
              />
            </Form.Item>
            <Form.Item name="purview" labelCol={{ span: 4 }} label="权限">
              <Select
                placeholder="选择权限"
                disabled
                options={doctorAll}
              />
            </Form.Item>
            <Form.Item name="password" labelCol={{ span: 4 }} label="账号密码">
              <Input
                value={
                  currentRecordRef.current
                    ? currentRecordRef.current.password
                    : ""
                }
                disabled
              />
            </Form.Item>
            <Form.Item name="idcard" labelCol={{ span: 4 }} label="身份证号">
              <Input
              disabled
                value={
                  currentRecordRef.current ? currentRecordRef.current.id : ""
                }
              />
            </Form.Item>
            <Form.Item name="phone" labelCol={{ span: 4 }} label="手机号">
              <Input
                disabled
                value={
                  currentRecordRef.current ? currentRecordRef.current.phone : ""
                }
              />
            </Form.Item>
            <Form.Item name="sex" labelCol={{ span: 4 }} label="性别">
              <Input
                 disabled
                value={
                  currentRecordRef.current ? currentRecordRef.current.sex : ""
                }
              />
            </Form.Item>
            <Form.Item name="url" labelCol={{ span: 4 }} label="头像">
              <div>
                  <img
                    alt="example"
                    style={{ width: '200px',height:'200px' ,borderRadius:'40px' }}
                    src={previewImage}
                  />
              </div>
            </Form.Item>
            <Form.Item>
              <div className={Department.director_btn_box}>
                  <Button
                    className={Department.btn}
                    type="primary"
                    onClick={handleOkItemClick}
                  >
                    确认
                  </Button>
              </div>
            </Form.Item>
          </Form>
        </Modal>


        <Flex gap="middle" vertical>
          <Flex align="center" gap="middle">
            <div className={Department.title}>
              <div className={Department.title_left}>
                <div className={Department.title_name}>姓名</div>
                <div>
                  <Input ref={inputRef} placeholder="请输入姓名查询" />
                </div>
                <Button
                  onClick={handleSearch}
                  type="primary"
                  className={Department.title_left_btn}
                >
                  <span
                    className="iconfont icon-ic_search24px"
                    style={{ color: "white" }}
                  ></span>
                  查询
                </Button>
              </div>
              <Button
                onClick={handleDeleteSelected}
                disabled={!hasSelected}
                loading={loading}
                type="dashed"
                danger
              >
                删除选中
              </Button>
            </div>
          </Flex>
          <Table
            bordered
            size="small"
            rowSelection={rowSelection}
            dataSource={data}
            pagination={false}
            rowClassName={Department.customTableCell}
            className={Department.customTableCell}
            rowKey="id"
          >
            {columns.map((col) => (
              <Table.Column
                className={Department.customTableCell}
                key={col.key}
                title={col.title}
                dataIndex={col.dataIndex}
                width={col.width}
                align={col.align}
                render={col.render}
              />
            ))}
          </Table>
          <div className={Department.paging_box}>
            共{total}条
            <Pagination
              size="small"
              className={Department.paging}
              current={currentPage}
              pageSize={pageSize}
              total={total}
              onChange={handlePageChange}
              onShowSizeChange={onShowSizeChange}
              showSizeChanger
              showQuickJumper
              pageSizeOptions={["10", "15"]}
              defaultCurrent={2}
            />
          </div>
        </Flex>
      </div>
    </>
  );
};

export default DepartmentManagement;
